/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {AutoComplete, Button, DatePicker, Form, Input, InputNumber, notification, Select, Table} from 'antd';

import {FormField, FormLayout, ModalFooter, SearchForm} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import notify from "../../../components/NotificationExtra";
import ViewTitle from "../../../components/ViewTitle";

moment.locale('zh-cn');
const table = 'material';
@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            material,
            treeNode, customer
          }) => ({...user, ...material, ...dynamicLabel, ...global, ...customer, ...treeNode}))
export default class ModalSelectMaterial extends FormBase {
  constructor(props) {
    super(props);
    const {values = {target: "自用"}} = this.props;
    const {code} = values;
    this.state = {...values, tagColor: undefined, selectedRowKeys: [code]};
  }

  componentDidMount() {
    const data = this.props.form.getFieldsValue();
    let {name, code} = data;
    name = name === '' ? undefined : name;
    code = code === '' ? undefined : code;
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    this.props.dispatch({
      type: 'material/findMany',
      payload: {name, code}
    });
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
  }

  renderFoot = () => {
    const {foot, value, callback, modalRef, type = "radio", form, values = {}, materials = []} = this.props;
    const {selectedRowKeys} = this.state;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            if (selectedRowKeys.length === 0) {
              notify({type: 'error', message: '未选择物料！'});
              return;
            }
            const selected = [];
            for (let code of selectedRowKeys) {
              const device = _.find(materials, item => {
                return item.code === code;
              });
              selected.push(device);
            }

            form.validateFields((err, _values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {pmLotId} = values;
              values.pmLotId = pmLotId ? pmLotId : 'PML' + moment().format('YYYY-MM-DD-HH-mm-ss');

              const material = selected[0];
              _.merge(material, _values);
              _.merge(values, material);

              console.log('sss', values);
              callback(values);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  onSelectChange = (selectedRowKeys, record) => {
    this.setState({...record, selectedRowKeys});
  };
  columns = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const {labels = []} = model;
    let temp = [
      {
        title: "物料", dataIndex: 'name', key: 'name', render: (value, record) => {
          const {code} = record;
          return this.getProductionElement(code, value);
        }
      },
      {
        title: '形态',
        dataIndex: 'subcategory',
        key: 'subcategory'
      },
      {
        title: '规格',
        dataIndex: 'spec',
        key: 'spec'
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type'
      }, {
        title: '编号',
        dataIndex: 'number',
        key: 'number'
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit'
      }
    ];

    temp.push(
      {
        title: '创建者',
        dataIndex: 'createUsername',
        key: 'createUsername',
        width: 160
      }
    );
    return temp;
  };

  getSearchFields = () => {
    const arr = [
      <FormField
        label="物料名称"
        name="name"
        key={1}
      >
        <Input allowClear placeholder="请输入物料名称"/>
      </FormField>,
      <FormField
        label="物料编码"
        name="code"
        key={2}
      >
        <Input allowClear placeholder="请输入物料编码"/>
      </FormField>
    ];
    return arr;
  };

  getList = (isUsed) => {
    const {values = {}, customers = []} = this.props;
    const {count, taxRate = "13%", price, customer, customerProject, shippingFee} = values;
    const {target = "自用"} = this.state;

    const temp = [<FormField
      label={'数量'}
      name={'count'}
      initialValue={count}
      required={true}
    >
      <InputNumber disabled={isUsed} style={{width: '100%'}}
      ></InputNumber>
    </FormField>,
      <FormField
        label={'含税单价'}
        name={'price'}
        initialValue={price}
      >
        <InputNumber style={{width: '100%'}} disabled={isUsed}
        ></InputNumber>
      </FormField>,
      <FormField
        label={'运费'}
        name={'shippingFee'}
        initialValue={shippingFee}
      >
        <InputNumber style={{width: '100%'}} disabled={isUsed}
        ></InputNumber>
      </FormField>,
      <FormField
        label={'去向'}
        name={'target'}
        required={true}
        initialValue={target}
      >
        <Select allowClear disabled={isUsed} style={{width: '100%'}} onSelect={value => {
          this.state.target = value;
        }}>
          {this.getSelectOption(["自用", '客用专项', '客用公用'])}
        </Select>
      </FormField>
    ];
    if (target === '客用专项') {
      temp.push(<FormField
        label={'客户'}
        name={'customer'}
        initialValue={customer}
      >
        <AutoComplete disabled={isUsed} style={{width: '100%'}}
                      dataSource={this.getOpt('customer', customers)}
                      filterOption={(inputValue, option) =>
                        option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                      }
                      allowClear
          // onSelect={this.onSelectCustomer}
        >
        </AutoComplete>
      </FormField>);
      temp.push(<FormField
        label={'客户项目'}
        name={'customerProject'}
        initialValue={customerProject}
      >
        <Input style={{width: '100%'}}></Input>
      </FormField>);
    }
    return temp;
  };

  render() {
    const {
      materials,
      footDisabled,
      style,
      values = {},
      form,
      selectedDevices
    } = this.props;

    const {
      selectedRowKeys, current = 1, loading, total = 0, code,
      name,
      subcategory = "", spec = "", type = "",
      number = ""
    } = this.state;
    const {useCount = 0} = values;
    const rowSelection = {
      type: "radio",
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: _.find(selectedDevices, item => {
          console.log(item.code, "disabled", record.code);
          return item.code === record.code;
        })
      })
    };
    const onSelectRow = (record) => {
      const {code} = record;
      const temp = _.find(selectedRowKeys, item => {
        return item === code;
      });
      if (temp) {
        _.remove(selectedRowKeys, item => item === code);
      } else {
        selectedRowKeys.length = 0;
        selectedRowKeys.push(record.code);
      }
      this.onSelectChange(selectedRowKeys, record);
    };
    const str = code ? `${name} ${subcategory} ${spec} ${type} ${number}` : "";
    return (
      <div style={{...style}}>

        {useCount > 0 && <div style={{marginLeft: '24px', color: '#f22'}}>{`* 物料 ${str} 已有订单占用。`}</div>}
        {useCount === 0 && <ViewTitle
          title={'选择物料'}
          subTitle={"已选择物料 " + str}
          actions={<Button type="primary"
                           onClick={() => {
                             window.open('/#/store/material');
                           }}
          >新建物料</Button>}
        ></ViewTitle>}

        {useCount === 0 && <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>}
        {useCount === 0 && <Table
          className={'antTable'}
          bordered
          rowSelection={rowSelection}
          loading={loading}
          rowKey={record => record.code}
          columns={this.columns()}
          type={type}
          dataSource={materials}
          onRow={(record) => ({
            onClick: () => onSelectRow(record)
          })}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
        >
        </Table>}
        <FormLayout form={form} cols={2}>
          {this.getList(useCount > 0)}
          {/*{target === '租用' && this.getZY()}*/}
        </FormLayout>
        {!footDisabled && this.renderFoot()}
      </div>
    );
  }
}

